package Backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 组合总和2 {

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    int[] candidates;
    int target;
    int sum = 0;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        this.candidates = candidates;
        this.target = target;
        backTracking(0);
        return res;
    }

    private void backTracking(int index) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (i > index && candidates[i] == candidates[i - 1]) continue;
            if (sum + candidates[i] > target) break;
            sum += candidates[i];
            path.add(candidates[i]);
            backTracking(i + 1);
            sum -= candidates[i];
            path.removeLast();
        }
    }
}
